package com.pt.pok.protobuf;

import com.google.protobuf.InvalidProtocolBufferException;
import com.pt.pok.CommandHandler;
import com.pt.pok.CommandListener;
import com.pt.pok.GeneralProxyException;
import com.pt.pok.generated.Commands;
import com.pt.pok.model.LoginRequest;
import com.pt.pok.model.PokerCommand;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author Roman.Ivanov@playtech.com, Andrey.Panfilov@playtech.com
 * @date 1/23/12 {@inheritDoc} LoginRequest Protobuf handler
 */
class LoginRequestCommandHandler
    implements CommandHandler<byte[]> {

    private final List<CommandListener> listeners = new CopyOnWriteArrayList<CommandListener>();

    private void notifyListeners(LoginRequest loginRequest) {
        for (CommandListener listener : listeners) {
            listener.onCommand(loginRequest);
        }
    }

    public void handle(byte[] data)
        throws GeneralProxyException {
        LoginRequest lr = unmarshalRequest(data);
        notifyListeners(lr);
    }

    private LoginRequest unmarshalRequest(byte[] data)
        throws GeneralProxyException {
        Commands.LoginRequest login;
        try {
            login = Commands.LoginRequest.newBuilder().mergeFrom(data).build();
        } catch (InvalidProtocolBufferException e) {
            throw new GeneralProxyException("Failed to build protobuf command " + Commands.LoginRequest.class, e);
        }
        LoginRequest lr = new LoginRequest();
        lr.setPassword(login.getPassword());
        lr.setUsername(login.getUsername());
        return lr;
    }

    public PokerCommand handleDirect(byte[] data)
        throws GeneralProxyException {
        return unmarshalRequest(data);
    }

    public void addListener(CommandListener loginRequestCommandListener) {
        listeners.add(loginRequestCommandListener);
    }

    public void removeListener(CommandListener commandListener) {
        listeners.remove(commandListener);
    }
}
